package com.trainingcloud.ctrl;

import com.alibaba.excel.EasyExcel;
import com.trainingcloud.mapper.ClassInfoMapper;
import com.trainingcloud.mapper.StudentInfoMapper;
import com.trainingcloud.pojo.ExcelUserData;
import com.trainingcloud.pojo.StudentInfo;
import com.trainingcloud.service.IUserService;
import com.trainingcloud.config.ExcelUserReadListener;
import com.trainingcloud.utils.MyFileUtil;
import com.trainingcloud.utils.ResultUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.trainingcloud.mapper.UserMapper;
import com.trainingcloud.pojo.User;
import com.trainingcloud.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 纸鹤
 * @since 2022-10-11
 */
@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClassInfoMapper classInfoMapper;

    @Autowired
    private StudentInfoMapper studentInfoMapper;

    @Value("${getTemplate}")
    private String filepath;

    //获取头像
    @RequestMapping("/getImg")
    public void getImg(String url, HttpServletResponse response) {
        System.out.println("访问图片：");
        System.out.println(url);
        MyFileUtil.getImg(url, response);
    }

    //    修改密码
    @RequestMapping("/updatePwd")
    public ResultUtil updatePwd(User user,String oldpwd,String newpwd) {
        System.err.println(user);
        ResultUtil resultUtil = ResultUtil.ok("修改成功");
        try {
            User sqluser = userMapper.selectById(user.getId());
            if(sqluser.getPassword().equals(oldpwd)){
                user.setPassword(newpwd);
                userMapper.updateById(user);
            }else{
                return ResultUtil.error("旧密码有误，修改失败");
            }
        }catch (Exception e){
            return ResultUtil.error(e.getMessage());
        }
        return resultUtil;
    }


    //免验证登录
    @RequestMapping("/verfiToken")
    public ResultUtil verfiToken(String token) {
        try {
            String id = TokenUtil.getItem(token, "id");
            User user = userMapper.selectById(id);
            ResultUtil res = ResultUtil.ok("token 验证成功");
            res.setData(user);
            return res;
        } catch (Exception e) {
            return ResultUtil.error("token 验证失败");
        }
    }

    //登录
    @RequestMapping("/login")
    public ResultUtil getUser(User user) {
        //根据User判断数据库是否存在账号密码
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //将前端与数据库中相同字段名进行匹配
        queryWrapper.eq("user_name", user.getUserName());
        queryWrapper.eq("password", user.getPassword());
        User one = userMapper.selectOne(queryWrapper);
        System.out.println(one);
        //如果one存在，返回token
        //如果失败则返回错误信息
        try {
            if (one != null && one.getUserName() != null) {
                ResultUtil resultUtil = ResultUtil.ok();
                //成功 创建token
                Map<String, String> data = new HashMap<>();
                data.put("userName", one.getUserName());
                data.put("id", one.getId() + "");
                data.put("userNick", one.getUserNick());
                data.put("password", one.getPassword());
                String token = TokenUtil.getToken(7, data);
                //将用户私密信息清除
                //one.setPassword(null);
                resultUtil.setData(one);
                resultUtil.setMsg(token);
                return resultUtil;
            } else {
                return ResultUtil.error("登录失败！账号或密码有误！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("登录失败！请联系管理员！");
        }
    }

    //根据班级ID查询班级成员
    @RequestMapping("/getStudentByClassId")
    public ResultUtil getStudentByClassId(int id) {
        ResultUtil ok = ResultUtil.ok();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", id);
        queryWrapper.eq("user_type", 0);
        List<User> users = userMapper.selectList(queryWrapper);
        ok.setData(users);
        return ok;
    }

    //添加单条学生数据
    @RequestMapping("/addStudent_Single")
    public ResultUtil addStudent_Single(User user) {
        ResultUtil ok = ResultUtil.ok();
        ok.setMsg("添加成功！");
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name", user.getUserName());
            List<User> users = userMapper.selectList(queryWrapper);
            if (users != null && users.size() > 0) {
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setRelationClassId(user.getStatus());
                studentInfo.setUserId(users.get(0).getId());
                studentInfoMapper.insert(studentInfo);
                return ok;
            }

            //根据班级id获取学生信息
            int i = userMapper.insert(user);
            StudentInfo studentInfo = new StudentInfo();
            studentInfo.setRelationClassId(user.getStatus());
            studentInfo.setUserId(user.getId());
            studentInfoMapper.insert(studentInfo);
        } catch (Exception e) {
            return ResultUtil.error(e.getMessage());
        }
        return ok;
    }

    //    uploadfile文件上传
    @RequestMapping("/uploadfileForUser")
    public ResultUtil uploadfile(MultipartFile file) {
        ResultUtil ok = ResultUtil.ok();
        try {
            EasyExcel.read(
                    file.getInputStream(),
                    ExcelUserData.class,
                    new ExcelUserReadListener(userMapper, classInfoMapper, studentInfoMapper)).sheet().doRead();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return ok;
    }


    //模板下载
    @RequestMapping("/getTemplate")
    public void getTemplate(HttpServletResponse response) {
        System.out.println(filepath);
        MyFileUtil.fileDownload(filepath,response);
    }

    //    修改学生信息
    @RequestMapping("/editStudent")
    public ResultUtil editStudent(User user) {
        ResultUtil ok = ResultUtil.ok();
        ok.setMsg("修改成功！");
        try {
            int insert = userMapper.updateById(user);
            if (insert != 1) {
                return ResultUtil.error("修改失败");
            }
        } catch (Exception e) {
            return ResultUtil.error(e.getMessage());
        }
        return ok;
    }

    //    删除学生信息
    @RequestMapping("/delStudent")
    public ResultUtil delStudent(int id) {
        ResultUtil ok = ResultUtil.ok();
        ok.setMsg("删除成功！");
        try {
            int insert = userMapper.deleteById(id);
            if (insert != 1) {
                return ResultUtil.error("删除失败");
            }
        } catch (Exception e) {
            return ResultUtil.error(e.getMessage());
        }
        return ok;
    }

    //    修改用户头像
    @RequestMapping("/changeUserAvatar")
    public ResultUtil changeUserAvatar(MultipartFile file, int id) {
        ResultUtil ok = ResultUtil.ok();
        try {
            String userAvatar = MyFileUtil.fileUpload("userAvatar", file);
            User user = new User();
            user.setId(id);
            user.setUserAvatar(userAvatar);
            userMapper.updateById(user);
            ok.setData(userAvatar);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ok;
    }
    //    获取资源
    @RequestMapping("/downLoadFile")
    public void downLoadFile(HttpServletResponse response, String url) {
        MyFileUtil.fileDownload(url,response);
    }


}


